<template>
  <BasicDrawer
    v-bind="$attrs"
    @register="registerDrawer"
    showFooter
    :title="getTitle"
    width="500px"
    @ok="handleSubmit"
  >
    <BasicForm @register="registerForm">
      <template #relateCode="{ model, field }">
        <Select
          :options="moduleList"
          v-model:value="model[field]"
          placeholder="请选择"
          style="width: 100%"
          showSearch
          optionFilterProp="name"
          :field-names="{ label: 'name', value: 'code' }"
          allow-clear
          @change="handleChangeRelateCode"
        />
      </template>
      <template #fieldSource="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="[
                {
                  label: 'ID',
                  value: 'id',
                },
                ...formGetFieldsData,
              ]"
              v-model:value="model[field]"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
              allow-clear
            />
            =
            <Select
              :options="fieldRelatedList"
              v-model:value="dataRef['fieldRelated']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
              allow-clear
            />
          </div>
          （无表示无主键对应关系）
        </FormItemRest>
      </template>
      <template #fieldOtherRelated="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="moduleFormGetFieldsData"
              v-model:value="model[field]"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
              allow-clear
            />
            =
            <Input
              v-model:value="dataRef['fieldOtherRelatedVal']"
              placeholder="请输入"
              style="flex: 1"
            />
          </div>
          （空值表示无条件）
        </FormItemRest>
      </template>
      <template #viewList="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            <Select
              :options="viewList"
              v-model:value="model[field]"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
              allow-clear
            />
            （暂不支持）
          </div>
        </FormItemRest>
      </template>

      <template #conds>
        <a-button
          :type="dataRef.conds && dataRef.conds.length ? 'primary' : 'default'"
          @click="handleConfiguration"
          title="当满足条件时，显示选项卡"
        >
          配置
        </a-button>
      </template>
      <template #queryName="{ model, field }">
        <FormItemRest>
          <div class="flex gap-10px items-center">
            {{ model[field] }}
            <a-button type="primary" @click="handleSelQuery()">选择查询</a-button>
            <a-button type="primary" @click="handleAddFields()">添加映射</a-button>
          </div>
        </FormItemRest>
      </template>
      <template #mapping>
        <FormItemRest>
          <div
            v-for="(item, ind) in queryCondMapList"
            :key="ind"
            class="flex gap-10px items-center mb-2"
          >
            <Select
              :options="[
                {
                  label: '无',
                  value: '',
                },
                { value: 'primaryKeyId', label: '主键ID' },
                ...formGetFieldsData,
              ]"
              v-model:value="item['field']"
              placeholder="请选择"
              style="flex: 1"
              showSearch
              optionFilterProp="label"
            />
            <arrow-right-outlined />
            <Select
              style="width: 160px"
              :options="condFieldList"
              v-model:value="item.value"
              :fieldNames="{ label: 'title', value: 'name' }"
              show-search
              optionFilterProp="title"
            />
            <close-outlined style="color: red; cursor: pointer" @click="handleFieldsDelete(ind)" />
          </div>
        </FormItemRest>
      </template>
    </BasicForm>
    <ConfigurationModal
      @register="registerConfigurationModal"
      @success="handleSuccessConfigurationModal"
    />
    <SelectSearchDataModal
      @register="registerSelectSearchDataModal"
      @success="handleSuccessSelectSearchDataModal"
    />
  </BasicDrawer>
</template>
<script lang="ts">
  import { defineComponent, ref, computed, unref, onMounted } from 'vue';
  import { BasicForm, useForm } from '/@/components/Form/index';
  import {
    formSchema,
    formSchema2,
    formSchema3,
    viewList,
    otherFormFields,
  } from './tabComponent.data';
  import { BasicDrawer, useDrawerInner } from '/@/components/Drawer';
  import { useModal } from '/@/components/Modal';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { getFormGetFields, getVisualGetCondField } from '/@/api/flowManage/flowManage';
  import { Form, Input, Select } from 'ant-design-vue';
  import { ArrowRightOutlined, CloseOutlined } from '@ant-design/icons-vue';
  import ConfigurationModal from '../configuration/index';
  import { getVisualGetFormFieldsWithModuleRelated } from '/@/api/module/module';
  import SelectSearchDataModal from '/@/views/formDesigner/ui/cloud/common/nestSheet/modules/selectSearchData/SelectSearchDataModal.vue';
  import { getModulesAll } from '/@/api/system/system';
  import { getVisualCreateSubTag, getVisualUpdateSubTag } from '/@/api/module/module';
  export default defineComponent({
    name: 'TabComponentDrawer',
    components: {
      BasicDrawer,
      BasicForm,
      FormItemRest: Form.ItemRest,
      Input,
      Select,
      ArrowRightOutlined,
      CloseOutlined,
      ConfigurationModal,
      SelectSearchDataModal,
    },
    emits: ['success', 'register'],
    setup(props, { emit }) {
      const isUpdate = ref(true);
      let dataRef = ref<Recordable>({});
      const formCode = ref('');
      const moduleCode = ref('');
      const type = ref('module');
      const moduleList = ref<Recordable[]>([]);
      const queryCondMapList = ref<Recordable>([]);
      const { createMessage, createWarningModal } = useMessage();

      const [registerForm, { resetFields, setFieldsValue, validate, updateSchema, resetSchema }] =
        useForm({
          labelWidth: 90,
          schemas: formSchema,
          showActionButtonGroup: false,
        });

      const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
        setDrawerProps({ confirmLoading: false });
        isUpdate.value = data?.isUpdate;
        formCode.value = data?.formCode;
        moduleCode.value = data?.moduleCode;
        type.value = data?.type;
        console.log('type.value', type.value);

        getFormGetFieldsData();
        if (type.value == 'module') {
          dataRef.value = {
            viewList: '0',
            fieldSource: 'id',
          };

          getVisualGetFormFieldsWithModuleRelatedData();
          await resetSchema(formSchema);
        } else if (type.value == 'simple') {
          await resetSchema(formSchema2);
        } else if (type.value == 'query') {
          queryCondMapList.value = [
            {
              field: '',
            },
          ];
          await resetSchema(formSchema3);
        }
        resetFields();
        if (unref(isUpdate)) {
          dataRef.value = data?.record ?? {};
          dataRef.value.newTagName = dataRef.value.tagName;
          dataRef.value.relateCode = dataRef.value.formRelated;
          dataRef.value.cwsStatus =
            dataRef.value.cwsStatus != null && dataRef.value.cwsStatus != undefined
              ? String(dataRef.value.cwsStatus)
              : '';
          if (dataRef.value.relateCode) {
            getOtherFormGetFieldsData(dataRef.value.relateCode);
          }
          if (type.value == 'module') {
            if (dataRef.value.tagUrl) {
              const tagUrl = JSON.parse(dataRef.value.tagUrl);
              dataRef.value.viewList = tagUrl.viewList;
              dataRef.value.fieldOtherRelated = tagUrl.fieldOtherRelated;
              dataRef.value.fieldOtherRelatedVal = tagUrl.fieldOtherRelatedVal;
            }
            updateSchema([
              {
                field: 'tagName',
                ifShow: false,
              },
            ]);
            updateSchema([
              {
                field: 'newTagName',
                ifShow: true,
              },
            ]);
            updateSchema([
              {
                field: 'viewList',
                componentProps: {
                  disabled: true,
                },
              },
            ]);
            // updateSchema([
            //   {
            //     field: 'fieldOtherRelated',
            //     ifShow: false,
            //   },
            // ]);
          } else if (type.value == 'simple') {
            updateSchema([
              {
                field: 'tagName',
                ifShow: false,
              },
            ]);
            updateSchema([
              {
                field: 'newTagName',
                ifShow: true,
              },
            ]);
            // updateSchema([
            //   {
            //     field: 'conds',
            //     ifShow: true,
            //   },
            // ]);
          } else if (type.value === 'query') {
            queryCondMapList.value = [];
            if (dataRef.value.tagUrl) {
              const tagUrl = JSON.parse(dataRef.value.tagUrl);
              dataRef.value.queryId = tagUrl.queryId;
              getQueryId();
              for (let v in tagUrl) {
                if (v != 'queryId' && v != 'conds') {
                  queryCondMapList.value.push({
                    field: v,
                    value: tagUrl[v],
                  });
                }
              }
            }
            updateSchema([
              {
                field: 'tagName',
                ifShow: false,
              },
            ]);
            updateSchema([
              {
                field: 'newTagName',
                ifShow: true,
              },
            ]);
            // updateSchema([
            //   {
            //     field: 'queryFieldDesc',
            //     ifShow: true,
            //   },
            // ]);
            updateSchema([
              {
                field: 'conds',
                ifShow: true,
              },
            ]);
          }
        } else {
          if (type.value == 'module') {
            updateSchema([
              {
                field: 'tagName',
                ifShow: true,
              },
            ]);
            updateSchema([
              {
                field: 'newTagName',
                ifShow: false,
              },
            ]);
            updateSchema([
              {
                field: 'viewList',
                componentProps: {
                  disabled: false,
                },
              },
            ]);
            updateSchema([
              {
                field: 'fieldOtherRelated',
                ifShow: true,
              },
            ]);
          } else if (type.value == 'simple') {
            updateSchema([
              {
                field: 'tagName',
                ifShow: true,
              },
            ]);
            updateSchema([
              {
                field: 'newTagName',
                ifShow: false,
              },
            ]);
            // updateSchema([
            //   {
            //     field: 'conds',
            //     ifShow: false,
            //   },
            // ]);
          } else if (type.value === 'query') {
            updateSchema([
              {
                field: 'tagName',
                ifShow: true,
              },
            ]);
            updateSchema([
              {
                field: 'newTagName',
                ifShow: false,
              },
            ]);
            // updateSchema([
            //   {
            //     field: 'queryFieldDesc',
            //     ifShow: false,
            //   },
            // ]);
            updateSchema([
              {
                field: 'conds',
                ifShow: false,
              },
            ]);
          }
        }
        setFieldsValue({
          ...dataRef.value,
        });
      });

      const getTitle = computed(() => (!unref(isUpdate) ? '新增' : '编辑'));

      const formGetFieldsData = ref([]);
      //获取数据
      const getFormGetFieldsData = () => {
        formGetFieldsData.value = [];
        try {
          if (!formCode.value) return;
          getFormGetFields({ formCode: formCode.value }).then((res) => {
            formGetFieldsData.value = res || [];
            formGetFieldsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
          });
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };

      const formFieldsWithModuleRelatedList = ref([]);
      //获取模块数据
      const getVisualGetFormFieldsWithModuleRelatedData = async () => {
        formFieldsWithModuleRelatedList.value = [];
        try {
          if (!moduleCode.value) return;
          await getVisualGetFormFieldsWithModuleRelated({ moduleCode: moduleCode.value }).then(
            async (res) => {
              formFieldsWithModuleRelatedList.value = res || [];
              formFieldsWithModuleRelatedList.value.forEach((item: Recordable) => {
                item.label = item.name;
              });
            },
          );
        } catch (err) {
          console.log('getFormGetFields', err);
        }
      };
      //模块change
      const handleChangeRelateCode = (val) => {
        console.log('handleChangeRelateCode', val);
        dataRef.value['fieldRelated'] = '';
        if (val) {
          getOtherFormGetFieldsData(val);
        }
      };

      const moduleFormGetFieldsData = ref<Recordable[]>([]);
      const fieldRelatedList = ref<Recordable[]>([]);
      //获取模块的字段
      const getOtherFormGetFieldsData = (val) => {
        moduleFormGetFieldsData.value = [];
        try {
          if (!val) return;
          getFormGetFields({ formCode: val }).then((res) => {
            moduleFormGetFieldsData.value = res || [];
            moduleFormGetFieldsData.value.forEach((item: Recordable) => {
              delete item.options;
              item.value = item.name;
              item.label = item.title;
            });
            fieldRelatedList.value = [...moduleFormGetFieldsData.value, ...otherFormFields];
          });
        } catch (err) {
          console.log('getOtherFormGetFieldsData', err);
        }
      };

      const [registerConfigurationModal, { openModal: openConfiguration }] = useModal();
      //组合条件配置
      const handleConfiguration = () => {
        openConfiguration(true, {
          list: dataRef.value.conds || [],
          formGetFieldsData: formGetFieldsData.value,
        });
      };

      const handleSuccessConfigurationModal = ({ value }) => {
        dataRef.value.conds = value;
        setFieldsValue({ conds: value });
      };

      async function handleSubmit() {
        try {
          console.log('handleSubmit dataRef', dataRef.value);
          const values = await validate();
          let formData = Object.assign({}, dataRef.value, values);
          if (type.value == 'module') {
            formData.relateCodeSel = formData.relateCode;
            const tagUrl = {
              fieldSource: formData.fieldSource,
              formRelated: formData.relateCode,
              fieldRelated: formData.fieldRelated,
              cwsStatus: formData.cwsStatus,
              viewList: formData.viewList,
              fieldOtherRelated: formData.fieldOtherRelated,
              fieldOtherRelatedVal: formData.fieldOtherRelatedVal,
              conds: formData.conds,
            };
            formData.tagUrl = JSON.stringify(tagUrl);
          } else if (type.value == 'query') {
            if (queryCondMapList.value.length) {
              let queryCondMap = {};
              queryCondMapList.value.forEach((item) => {
                queryCondMap[item.field] = item.value;
              });
              queryCondMap['queryId'] = formData.queryId;
              formData.tagUrl = JSON.stringify(queryCondMap);
            } else {
              formData.tagUrl = '';
            }
          }
          formData.type = type.value;
          formData.moduleCode = moduleCode.value;
          formData.formCode = formCode.value;
          console.log('formData', formData);
          setDrawerProps({ confirmLoading: true });
          if (!unref(isUpdate)) {
            await getVisualCreateSubTag(formData);
          } else {
            await getVisualUpdateSubTag(formData);
          }
          createMessage.success('操作成功');
          closeDrawer();
          emit('success');
        } finally {
          setDrawerProps({ confirmLoading: false });
        }
      }
      const fetch = async () => {
        moduleList.value = (await getModulesAll()) || [];
      };

      // function setChildren(node) {
      //   node.forEach((item) => {
      //     item.key = item.code;
      //     item.value = item.code;
      //     item.title = item.name;
      //     item.disabled = item.layer == 3 ? false : true;
      //     if (item.children && Array.isArray(item.children) && item.children.length > 0) {
      //       item.isLeaf = false;
      //       setChildren(item.children);
      //     } else {
      //       item.isLeaf = true;
      //     }
      //   });
      //   return node;
      // }
      onMounted(fetch);

      const [registerSelectSearchDataModal, { openModal: openSelectSearchDataModal }] = useModal();
      const handleSuccessSelectSearchDataModal = (record) => {
        console.log('handleSuccessSelectSearchDataModal', record);
        dataRef.value.queryName = record.queryName;
        dataRef.value.queryId = record.id;
        setFieldsValue({ queryName: dataRef.value.queryName });
        getQueryId();
      };
      //选择查询
      const handleSelQuery = () => {
        // queryId
        openSelectSearchDataModal(true, {});
      };
      //添加映射
      const handleAddFields = () => {
        queryCondMapList.value.push({
          field: '',
        });
      };
      //删除映射
      const handleFieldsDelete = (index) => {
        queryCondMapList.value.splice(index, 1);
      };

      const condFieldList = ref<Recordable[]>([]);

      //获取关联查询id
      const getQueryId = () => {
        condFieldList.value = [];
        try {
          if (dataRef.value.queryId == 0) {
            condFieldList.value = [];
            return;
          }
          getVisualGetCondField({ id: dataRef.value.queryId }).then((res) => {
            condFieldList.value = res || [];
          });
        } catch (err) {
          console.log('getVisualGetCondField', err);
        }
      };
      return {
        registerDrawer,
        registerForm,
        getTitle,
        handleSubmit,
        isUpdate,
        registerConfigurationModal,
        handleSuccessConfigurationModal,
        handleConfiguration,
        dataRef,
        // treeData,
        handleChangeRelateCode,
        viewList,
        formFieldsWithModuleRelatedList,
        formGetFieldsData,
        moduleFormGetFieldsData,
        handleSelQuery,
        handleAddFields,
        handleFieldsDelete,
        registerSelectSearchDataModal,
        handleSuccessSelectSearchDataModal,
        moduleList,
        fieldRelatedList,
        condFieldList,
        queryCondMapList,
      };
    },
  });
</script>
